package de.sas.za_gui.shell;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;

public class GameHandler
{
	private static double startPopulation = 0.31;
	Cell[][] field;

	Thread[][] threads = new Thread[5][5];
	CyclicBarrier barrier = new CyclicBarrier(threads.length * threads[0].length + 1);
	int cycleCount = 0;
	int width;
	int height;

	public Cell[][] getField()
	{
		return field;
	}

	public GameHandler(int width, int height, double startPop, List<Integer> allowedToGetAlive, List<Integer> allowedToStayAlive)
	{
		field = new Cell[width][height];
		this.width = field.length / threads.length;
		this.height = field[0].length / threads[0].length;
		startPopulation = startPop;
		Computer.allowedToGetAlive = allowedToGetAlive;
		Computer.allowedToStayAlive = allowedToStayAlive;
		initField();
	}

	private void initField()
	{
		Random random = new Random();
		for (int x = 0; x < field.length; x++)
		{
			for (int y = 0; y < field[0].length; y++)
			{
				field[x][y] = new Cell(false);
			}
		}
		int stop = (int) (startPopulation * (field.length * field[0].length));
		for (int i = 0; i < stop; i++)
		{
			boolean isAlive = false;
			do
			{
				int x = random.nextInt(field.length);
				int y = random.nextInt(field[0].length);
				isAlive = field[x][y].isAlive();
				field[x][y] = new Cell(true);

			} while (isAlive);
		}
	}

	public void nextStep()
	{
		Computer.field = this.field;
		for (int i = 0; i < threads.length; i++)
		{
			int x = this.width * i;
			int width = i == threads.length - 1 ? field.length - x : this.width;
			for (int j = 0; j < threads[0].length; j++)
			{
				int y = this.height * j;
				int height = j == threads[0].length - 1 ? field[0].length - y : this.height;
				threads[i][j] = new Thread(new Computer(barrier, x, y, width, height));
				threads[i][j].start();
			}
		}
		try
		{
			barrier.await();
			cycleCount++;
			barrier.await();
			System.out.println(getPercentageAlive());
		}
		catch (Exception err)
		{

		}
	}

	private double getPercentageAlive()
	{
		int count = 0;
		for (int i = 0; i < field.length; i++)
		{
			for (int j = 0; j < field[0].length; j++)
			{
				if (field[i][j].isAlive())
				{
					count++;
				}
			}
		}
		return (double) count / (field.length * field[0].length);
	}
}
